#include "IndexBuffer.h"
#include "..\utils\Log.h"

namespace ds {

IndexBuffer::IndexBuffer(uint32 maxIndices,bool dynamic) : m_MaxIndices(maxIndices) , m_Dynamic(dynamic) {
	IDirect3DDevice9 * pDevice = gEngine->getDevice();
	D3DPOOL pool = m_Dynamic ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED; 
	DWORD usage = m_Dynamic ? D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC : D3DUSAGE_WRITEONLY; 			
	HR(pDevice->CreateIndexBuffer( m_MaxIndices * sizeof(WORD),usage,D3DFMT_INDEX16,pool,&indexBuffer,NULL));	
	LOG(logINFO) << "new IndexBuffer created size: " << maxIndices << " dynamic: " << dynamic;
}


IndexBuffer::~IndexBuffer() {
	SAFE_RELEASE(indexBuffer);
}

void IndexBuffer::addIndices(uint32 indexArray[],uint32 count) {
	if ( ( m_Indices.size() + count ) <= m_MaxIndices ) {
		for ( int i = 0; i < count; ++i ) {
			m_Indices.push_back(indexArray[i]);
		}
	}
	else {
		LOG(logERROR) << "IndexBuffer - addIndex : maximum exceeded size: " << m_Indices.size() << " max: " << m_MaxIndices;
	}
}

void IndexBuffer::addIndex(uint32 idx) {
	if ( m_Indices.size() <= m_MaxIndices ) {
		m_Indices.push_back(idx);
	}
	else {
		LOG(logERROR) << "IndexBuffer - addIndex : maximum exceeded size: " << m_Indices.size() << " max: " << m_MaxIndices;
	}
}

void IndexBuffer::clear() {
	m_Indices.clear();
}

bool IndexBuffer::init() {
	int numVerts = getSize();
	if ( numVerts > 0 ) {	    			
	    WORD *pIndex;
		HR(indexBuffer->Lock( 0, sizeof(WORD), ( void** )&pIndex, 0 ));					
		for ( int i = 0; i < numVerts; ++i) {		
			pIndex[i] = m_Indices[i];	
		}
	    HR(indexBuffer->Unlock());
	}	
    return true;
}

};
